package burubaka.service;

import java.util.List;

import org.slim3.datastore.Datastore;

import burubaka.BurubakaConstants;
import burubaka.common.BurubakaUtil;
import burubaka.meta.HandicappingMeta;
import burubaka.model.Handicapping;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.Transaction;

public class HandicappingService {

	HandicappingMeta meta = new HandicappingMeta();

	/**
	 * 先祖キーから予想一覧を取得
	 * 
	 * @return Handicapping
	 */
	public List<Handicapping> findHandicappingByAncKey(Key anckey) {
		return Datastore.query(meta, anckey).asList();
	}

	/**
	 * 先祖キーから予想一覧を取得
	 * 
	 * @return Handicapping
	 */
	public List<Handicapping> findHandicappingByAncKey(Key anckey, String year) {
		return Datastore.query(meta, anckey).filter(meta.raceDate.startsWith(year)).asList();
	}

	/**
	 * 予想を取得
	 * 
	 * @return Handicapping
	 */
	public Handicapping getHandicapping(Key key, String raceDate) {
		return Datastore.query(meta, key).filter(meta.raceDate.equal(raceDate)).asSingle();
	}

	/**
	 * 予想一覧を取得
	 * 
	 * @return Handicapping
	 */
	public List<Handicapping> getHandicappingList(String raceDate) {
		return Datastore.query(meta).filter(meta.raceDate.equal(raceDate)).sort(meta.updTime.desc).asList();
	}

	/**
	 * 予想一覧を取得
	 * 
	 * @return Handicapping
	 */
	public List<Handicapping> getHandicappingListOrderByWithdrawal(String raceDate) {
		return Datastore.query(meta).filter(meta.raceDate.equal(raceDate)).sort(meta.withdrawal.desc).asList();
	}

	/**
	 * 配当計算が完了していない現在予想一覧を取得
	 * 
	 * @return Handicapping
	 */
	public List<Handicapping> getCalculatingHandicapping(String raceDate) {
		return Datastore.query(meta)
				.filter(meta.raceDate.equal(raceDate), meta.payOffFlag.equal(BurubakaConstants.FLAG_ON)).asList();
	}

	/**
	 * 登録
	 * 
	 * @param model
	 * @return Handicapping
	 */
	public Handicapping regist(Handicapping model) {
		Transaction tx = Datastore.beginTransaction();
		model.setUpdTime(BurubakaUtil.getCalendarInstance().getTime());
		Datastore.put(model);
		tx.commit();
		return model;
	}

	/**
	 * 登録
	 * 
	 * @param model
	 * @param ancKey
	 * @return Handicapping
	 */
	public Handicapping regist(Handicapping model, Key ancKey) {
		Transaction tx = Datastore.beginTransaction();
		if (model.getKey() == null) {
			Key childKey = Datastore.allocateId(ancKey, Handicapping.class);
			model.setKey(childKey);
		}
		model.setUpdTime(BurubakaUtil.getCalendarInstance().getTime());
		Datastore.put(model);
		tx.commit();
		return model;
	}

	public Handicapping jsonToModel(String json) {
		return meta.jsonToModel(json);
	}

	/**
	 * 予想とマークシートを削除する
	 * 
	 * @param key
	 * @return ture:成功
	 */
	public boolean deleteAll(Key key) {
		Transaction tx = Datastore.beginTransaction();
		Datastore.deleteAll(key);
		tx.commit();
		return true;
	}
}
